/*
 *  Copyright 2013 Utkin Dmitry
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */


#include <QDebug>
#include <QThread>
#include <QAtomicInt>
#include <QHostAddress>
#include <QCoreApplication>
#include <protoqtrpc/RpcController.h>
#include <protoqtrpc/SocketRpcChannel.h>
#include <protoqtrpc/BlockingClosure.h>
#include "protoqtrpc/test/TestService.pb.h"

#define THREADS 100
#define CALLS 40
#define REQUEST_SIZE 1024



#define TEST(expr, msg)\
    if (!(expr)) { qWarning() << __FILE__ << ":" << __LINE__ << " TEST failed:" << msg; ::exit(1); }

class ClientTest: public QThread
{
public:
    inline ClientTest():
        mCallNum(0), mChannel(QHostAddress("127.0.0.1"), 33601), mClientStub(&mChannel)
    {
    }

protected:
    virtual void run()
    {
        mChannel.setTimeout(60000);

        mRequest.mutable_request()->resize(REQUEST_SIZE, 'A');

        mCallNum = CALLS;
        for (int i = 0; i < CALLS; ++i)
        {
            mClientStub.echo(&mControllers[i], &mRequest, &mResponses[i],
                             ::google::protobuf::NewCallback(this, &ClientTest::responseReceived, i));
        }

        exec();
    }

    void responseReceived(int index)
    {
        TEST(!mControllers[index].Failed(), mControllers[index].ErrorText().c_str());
        TEST(mResponses[index].response() == mRequest.request(), "response != request");
        if (!--mCallNum)
            quit();
    }

private:
    int mCallNum;
    protoqtrpc::SocketRpcChannel mChannel;
    protoqtrpc::test::TestRequest mRequest;
    protoqtrpc::test::TestResponse mResponses[CALLS];
    protoqtrpc::RpcController mControllers[CALLS];
    protoqtrpc::test::TestService::Stub mClientStub;
    std::string mRequestStr;
};


int main(int argc, char** argv)
{
    QCoreApplication app(argc, argv);

    ClientTest* clients[THREADS];

    for (int i = 0; i < THREADS; ++i)
        (clients[i] = new ClientTest)->start();

    for (int i = 0; i < THREADS; ++i)
        clients[i]->wait();


    qDebug() << "Tests OK";

    return 0;
}
